<?php
class Messages_model extends CI_Model {

	function __construct(){
		parent::__construct();
	}

	function getMessages($type){
		$email = isset($_SESSION['email'])? $_SESSION['email']:'';//$this->session->userdata('email');
		$query = $this->db->query("SELECT a.*, reverse(sha1(concat(a.messageid,a.userid,a.type))) as pdf_id
		                           FROM mlme_messages a,mlme_users b
								   WHERE a.userid = b.userid AND a.type = '".$type."' AND b.email = '".$email."'
								   ORDER BY messageid DESC
									");

		$data = array();
		if ($query->num_rows() > 0){
				foreach ($query->result() as $row){
				   $data[]=$row;
				}
			}
			return $data;
		}

	/**
	 * Get certain message
	 */

	 function getMessage($id){
	 	$this->db->where('messageid',$id);
	 	$this->db->LIMIT(1);
	 	$query = $this->db->get('mlme_messages');
	 	return $query->row_array();
	 }

	function addMessages(){
			$userid = $this->get_userid($_SESSION['email']);
			$type = $this->input->post('type');
			$linksS = '';
			$vid = array();
			//youtube links if any
			if($type == 'videos'){
				$linksA = $this->input->post('ylinks', array());
				if(!empty($linksA)){
					foreach($linksA as $url){
						if(strlen($url)){
							parse_str( parse_url( $url, PHP_URL_QUERY ) );
							$vid[] = $v;
						}
					}
					$linksS = implode("\n", $vid);
				}
			}

			$newMessages = array(
				'userid' => $userid,
				'subject' => $this->input->post('m-subject'),
				'description' => $this->input->post('m-message'),
				'totype' => $this->input->post('totype'),
				'date_added' => date('Y-m-d h:m:s'),
				'type' => $type,
				'links' => $linksS
			 	);
		$insert = $this->db->insert('mlme_messages', $newMessages);
		return $this->db->insert_id();
	}

	function countMessages($type){
		$userid = $this->get_userid($_SESSION['email']);
		$query = $this->db->query("SELECT messageid FROM mlme_messages WHERE userid = '".$userid."' AND type = '".$type."'");
		return $query->num_rows();

	}

	function deleteMessage($id=array()){
		if( empty($id) ) return false;
		$this->db->where_in( 'messageid', $id );
		return $this->db->delete('mlme_messages');
	}
	function deleteMessageFile($id=array()){
		if( empty($id) ) return false;
		$this->db->where_in('messageid',$id);
		$this->db->delete('mlme_messages_files_x');
	}

	function get_userid($email){
		 $query = $this->db->query("SELECT userid FROM mlme_users WHERE email ='".$email."'");
		 $result = $query->row();
		 return $result->userid;
	}


}// end of Model


